<template>
  <div class="search-suggestion-container">
    <van-cell-group>
      <van-cell
        class="van-ellipsis"
        icon="search"
        v-for="(text, index) in suggestions"
        :key="index"
        @click="$emit('search', text)"
      >
        <div slot="title" v-html="highlight(text)"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSearchSuggestion } from '../../api/search'
import { debounce } from 'lodash'

export default {
  name: 'searchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: [] // 联想建议数据列表
    }
  },
  methods: {
    highlight (str) {
      return str.replace(
        new RegExp(this.searchText, 'gi'),
        `<span style="color: red;">${this.searchText}</span>`
      )
    }
  },
  watch: {
    searchText: {
      // debounce() 函数，lodash库防抖动/节流函数
      handler: debounce(async function () {
        console.log(this.searchText)
        const { data: { data: { options: res } } } = await getSearchSuggestion(this.searchText)
        console.log(res)
        this.suggestions = res
      }, 250),
      immediate: true // 该回调将会在侦听开始之后被立即调用
    }
  }
}
</script>

<style scoped>

</style>
